import requests
import base64
import gradio as gr

API_KEY = "Wqi3hfkjhKofFfSzyQRxuRKB"
SECRET_KEY = "V4eeFgSdG5f9poh7wfkr6IKmJnlc66RB"

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    response = requests.post(url, params=params)
    if response.status_code == 200:
        result = response.json()
        if 'access_token' in result:
            return result['access_token']
        else:
            print("获取Access Token失败：", result.get('error_description', '未知错误'))
            return None
    else:
        print("获取Access Token失败：", response.status_code, response.text)
        return None

def car_type_recognition(image_path):
    """
    识别图片中的车型
    :param image_path: 图片的路径
    """
    # 读取图片并编码为base64
    try:
        with open(image_path, 'rb') as f:
            img_base64 = base64.b64encode(f.read()).decode('utf-8')
    except Exception as e:
        print(f"读取图片失败：{e}")
        return
    # 构建请求体
    params = {
        "image": img_base64,
        "top_num": 5
    }
    # 获取Access Token
    access_token = get_access_token()
    if not access_token:
        print("无法获取有效的Access Token")
        return
    # 构造请求URL
    url = f"https://aip.baidubce.com/rest/2.0/image-classify/v1/car?access_token={access_token}"

    # 设置请求头
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    # 发送请求
    response = requests.post(url, data=params, headers=headers)
    # 处理响应
    if response.status_code == 200:
        result = response.json()
        if 'result' in result:
            # 根据 score 排序，选择得分最高的车型
            car_types = result['result']
            top_car = sorted(car_types, key=lambda x: x['score'], reverse=True)[0]

            text = "识别到的车型：" + top_car['name'] + "，年份：" + top_car['year']
            print(text)
            return text
            # 输出得分最高的车型及年份
            # print(f"识别到的车型：{top_car['name']}，年份：{top_car['year']}")
        else:
            print("识别失败：未能获取到有效的车型信息")
    else:
        print("请求失败：", response.status_code, response.text)

if __name__ == '__main__':
    image_path = r'imgs/baks/Quicker_20220930_181044.png'  # 图片路径
    car_type_recognition(image_path)

